package com.yincai.carefreewater.tool;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;


import com.yincai.carefreewater.R;
import com.yincai.carefreewater.base.MyApplication;
import com.yincai.carefreewater.constant.URLConstant;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;



/**
 * 升级
 */
public class VersionTools {
    // 更新应用版本标记
    private static final int UPDARE_TOKEN = 0x29;
    // 准备安装新版本应用标记
    private static final int INSTALL_TOKEN = 0x31;
    // 进度条的当前刻度值
    private int curProgress;
    private static final String FILE_PATH = Environment.getExternalStorageDirectory() + File.separator +"autoupdate" + File.separator;
    // 下载应用存放全路径
    private static final String FILE_NAME = FILE_PATH + "autoupdate.apk";
    private boolean isCancel;
    private Dialog dialog;
    private static Context mContext;
    private ProgressBar mProgress;
    private int vercode;
    private String down;
    private String jsonString;
    public static VersionTools version;
    public static VersionTools getIntence(){

        if (version==null){
            version=new VersionTools();
        }
        return version;
    }
    /**
     * 获取版本号
     */

    public void getVersionNumber(Context mContext){
        this.mContext=mContext;
        try {
            PackageManager manager=mContext.getPackageManager();
            PackageInfo info=manager.getPackageInfo(mContext.getPackageName(), PackageManager.GET_CONFIGURATIONS);
            vercode=info.versionCode;
            Map<Object,Object> map=new HashMap<>();
            OkHttpTool instance = OkHttpTool.getInstance();
            OkHttpClient client = instance.getOkHttpClient();
            Request request = new Request.Builder()
                    .url(URLConstant.HOST+URLConstant.VER_JSON)
                    .build();
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                }
                @Override
                public void onResponse(Call call, Response response) throws IOException {

                    Message msg=handler.obtainMessage(1,response.body().string());
                    handler.sendMessage(msg);
                }
            });

        }
        catch (Exception e){
            e.printStackTrace();
        }

    }


    private String TAG="tag";
    /**
     * {"code":403,"result":{"path":""},"msg":"暂无版本更新!","version":"1.0.0"}
     *
     *
     */
    private Handler handler=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            try {
                jsonString= (String) msg.obj;
                Log.i(TAG, "软件版本更新信息: "+ jsonString);
                JSONObject result=new JSONObject(jsonString);

                String code=result.optString("code");
                if (code.equals("100")){
                    // 获取packagemanager的实例
                    PackageManager packageManager =mContext.getPackageManager();
                    // getPackageName()是你当前类的包名，0代表是获取版本信息
                    PackageInfo packInfo = packageManager.getPackageInfo(mContext.getPackageName(),0);
                    String version = packInfo.versionName;
                    JSONObject res=result.getJSONObject("result");
                    String ver=res.optString("version_code","");
                    down=res.optString("file","");
                    long size=res.optLong("size",0);
                    Log.i(TAG, "handleMessage: "+ ver);
                    double int_old = 0;
                    double int_new= 0;
                    try {
                        int_old = Double.parseDouble(version);
                        int_new = Double.parseDouble(ver);
                        if ((int_new-int_old)>0){
                            showDialog(size);
                        }
                        else {
                            ToastTool.toast("当前软件已是最新版本");
                        }
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }


                }
            }
            catch (Exception e){
                e.printStackTrace();
            }

            return false;
        }
    });
    private Handler handlers=new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what){
                case UPDARE_TOKEN://设置进度
                    mProgress.setProgress(curProgress);
                    break;
                case INSTALL_TOKEN://下载完成
                    installApp();
                    break;
            }

            return false;
        }
    });
    private String message = "检测到本程序有新版本发布，建议您更新！";

    /**
     * 弹出升级按钮
     */
    private void showDialog(final Long size){
        new AlertDialog.Builder(mContext).setTitle("版本更新").setMessage(message).setPositiveButton("升级", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                showDownProgress();
                if(down.length()>0){
                    //开始下载
                    downloadApp(URLConstant.HOST+down,size);
                }
            }
        }).setNegativeButton("忽略", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        }).create().show();
    }

    /**
     * 下载弹窗
     */
    private void showDownProgress(){
        View view= LayoutInflater.from(mContext).inflate(R.layout.down_prograss,null);
        mProgress= (ProgressBar) view.findViewById(R.id.down_progressBars);
        AlertDialog.Builder builder=new AlertDialog.Builder(mContext);
        builder.setTitle("版本更新中");
        builder.setView(view);
        builder.setMessage("点击取消终中断下载");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                isCancel = true;
            }
        });
        dialog = builder.create();
        dialog.setCancelable(false);
        dialog.show();
    }
    /**
     * 下载下载开始
     */

    public void downloadApp(final String path, final Long size){
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL url=null;
                HttpURLConnection connection;
                FileOutputStream out = null;
                InputStream in = null;
                try{
                    url=new URL(path);
                    connection= (HttpURLConnection) url.openConnection();
                    connection.connect();
                    long length=size;//长度
                    in=connection.getInputStream();
                    File file=new File(FILE_PATH);
                    if (!file.exists()){
                        file.mkdir();
                    }
                    out=new FileOutputStream(new File(FILE_NAME));
                    byte[]buffer=new byte[1024];
                    int len=in.read(buffer);
                    long readedLength=0 ;
                    while (len!=-1){
                        // 用户点击“取消”按钮，下载中断
                        if(isCancel) {
                            break;
                        }
                        out.write(buffer,0,len);
                        readedLength += len;
                        curProgress = (int) (((float) readedLength /length) * 100);
                        handlers.sendEmptyMessage(UPDARE_TOKEN);
                        len=in.read(buffer);
                    }
                    if(readedLength >=length) {
                        dialog.dismiss();
                        // 下载完毕，通知安装
                        handlers.sendEmptyMessage(INSTALL_TOKEN);
                    }
                    out.flush();//刷新
                    out.close();//关闭输出
                    in.close();//关闭输入流
                    connection.disconnect();//中断连接
                }
                catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
    }
    /**
     * 安装新版本应用
     */
    public void installApp() {
        File appFile = new File(FILE_NAME);
        if(!appFile.exists()) {
            return;
        }
        // 跳转到新版本应用安装页面
        Intent intent = new Intent(Intent.ACTION_VIEW);
//判断是否是AndroidN以及更高的版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(MyApplication.getInsatence(),"com.yincai.carefreewater.fileProvider", appFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(appFile), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        mContext.startActivity(intent);

//        Intent intent = new Intent(Intent.ACTION_VIEW);
//        intent.setDataAndType(Uri.parse("file://" + appFile.toString()), "application/vnd.android.package-archive");
//        mContext.startActivity(intent);
    }
}
